# Simple AJAX chess website - User related handlers
#
# Copyright (C) 2008  Hong Anh Khoa
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from google.appengine.api import users

from basehandler import BaseRequestHandler
from google.appengine.ext.webapp.util import login_required
from datamodel import *

import datetime
import pickle
from modules.ChessBoard import ChessBoard

class OnlineUserHandler(BaseRequestHandler):

  def get(self):
    # Get online users list
    
    ltime = datetime.datetime.now() - datetime.timedelta(seconds = 60)
    
    # Users in rooms
    rusers = RoomPlayer.gql("WHERE access>=:1", ltime).fetch(100)
    
    # Other users
    musers = Player.gql("WHERE access>=:1", ltime).fetch(100)
    
    users = rusers + musers
    
    res = self.generate("userlist.tpl.html", {"users": users})
    
    self.response.out.write(res)
    

class RoomPresenceHandler(BaseRequestHandler):

  def get(self, roomid):
    # Update user presence in room
    room = Room.get(roomid)

    user = users.get_current_user()
    
    if user is None:
      return
      
    presence = RoomPlayer.gql("WHERE room=:1 AND user=:2", room, user).get()
    if presence is None: presence = RoomPlayer(room = room, user = user)
    presence.put()
    
    # Update room status
    game = Game.gql("WHERE room=:1 AND playing=:2", room, True).get()
    
    if game is None:
      room.status = "Waiting"
    else: 
      gameobj = pickle.loads(game.gameobject)
      if gameobj.getGameResult() != ChessBoard.NO_RESULT:
        room.status = "Just finished"
      else:
        room.status = "Playing"
    
    # Update the number of users in room
    
    ltime = datetime.datetime.now() - datetime.timedelta(seconds = 60)
    room.users = RoomPlayer.gql("WHERE room=:1 AND access>=:2", room, ltime).count()
    room.put()

    
class PresenceHandler(BaseRequestHandler):
  
  def get(self):
  
    # Update user presence time
    
    user = users.get_current_user()
    
    if user is not None:
      player = Player.gql("WHERE user=:1", user).get()
      if player is None:
        player = Player(user = user)
      
      player.put()
      

class RoomUserListHandler(BaseRequestHandler):

  def get(self, roomid):
    # List of users in room
    room = Room.get(roomid)
    ltime = datetime.datetime.now() - datetime.timedelta(seconds = 60)
    
    users = RoomPlayer.gql("WHERE room=:1 AND access>=:2", room, ltime)
    
    res = self.generate("roomuser.tpl.html", {"users": users})
    
    self.response.out.write(res)
    

class FinishedGameListHandler(BaseRequestHandler):
  
  @login_required
  def get(self):
    # Get all games played by user
    user = users.get_current_user()
    
    # Game played as white
    wgames = Game.gql("WHERE white=:1 AND result!=:2", user, None).fetch(100)
    
    # Game played as black
    bgames = Game.gql("WHERE black=:1 AND result!=:2", user, None).fetch(100)
    
    games = wgames + bgames
    
    res = self.generate("finishedgamelist.tpl.html", {"games": games})
    
    self.css = ["gamelist.css"]
    self.response.out.write(self.generate_page({"content": res}))
    

class CurrentGameListHandler(BaseRequestHandler):
  
  @login_required
  def get(self):
    # Get all current game
    
    user = users.get_current_user()
    
    # Game played as white
    wgames = Game.gql("WHERE white=:1 AND result=:2", user, None).fetch(100)
    
    # Game played as black
    bgames = Game.gql("WHERE black=:1 AND result=:2", user, None).fetch(100)
    
    games = wgames + bgames
    
    res = self.generate("currentgamelist.tpl.html", {"games": games})
    
    self.css = ["gamelist.css"]
    self.response.out.write(self.generate_page({"content": res}))
